#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MAX_EVENTS 1024
#define EVENT_LOOP_TIMEOUT 100 // ms

// 事件结构体
typedef struct event_handler_s {
    int fd;
    int events;
    void (*callback)(int fd, int events, void *arg);
    void *arg;
    struct event_handler_s *next; // 可选：用于链表管理
} event_handler_t;

// 事件库上下文
typedef struct event_loop_s {
    int epoll_fd;
    event_handler_t *handlers[MAX_EVENTS]; // 直接使用 fd 作为索引，简化管理
} event_loop_t;

// 创建事件循环
event_loop_t *event_loop_create() {
    event_loop_t *loop = (event_loop_t *)malloc(sizeof(event_loop_t));
    if (!loop) {
        perror("malloc failed");
        return NULL;
    }
    loop->epoll_fd = epoll_create1(0);
    if (loop->epoll_fd == -1) {
        perror("epoll_create1 failed");
        free(loop);
        return NULL;
    }
    memset(loop->handlers, 0, sizeof(loop->handlers));
    return loop;
}

// 注册事件处理器
int event_add(event_loop_t *loop, int fd, int events, void (*callback)(int, int, void *), void *arg) {
    if (fd < 0 || fd >= MAX_EVENTS || !loop || !callback) {
        errno = EINVAL;
        perror("event_add: invalid arguments");
        return -1;
    }

    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = events;

    if (epoll_ctl(loop->epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
        perror("epoll_ctl add failed");
        return -1;
    }

    event_handler_t *handler = (event_handler_t *)malloc(sizeof(event_handler_t));
    if (!handler) {
        perror("malloc failed");
        epoll_ctl(loop->epoll_fd, EPOLL_CTL_DEL, fd, NULL); // 清理已添加的 epoll
        return -1;
    }
    handler->fd = fd;
    handler->events = events;
    handler->callback = callback;
    handler->arg = arg;
    loop->handlers[fd] = handler;

    return 0;
}

// 修改事件处理器
int event_mod(event_loop_t *loop, int fd, int events) {
    if (fd < 0 || fd >= MAX_EVENTS || !loop) {
        errno = EINVAL;
        perror("event_mod: invalid arguments");
        return -1;
    }

    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = events;

    if (epoll_ctl(loop->epoll_fd, EPOLL_CTL_MOD, fd, &ev) == -1) {
        perror("epoll_ctl mod failed");
        return -1;
    }

    if (loop->handlers[fd]) {
        loop->handlers[fd]->events = events;
    }

    return 0;
}

// 删除事件处理器
int event_del(event_loop_t *loop, int fd) {
    if (fd < 0 || fd >= MAX_EVENTS || !loop) {
        errno = EINVAL;
        perror("event_del: invalid arguments");
        return -1;
    }

    if (epoll_ctl(loop->epoll_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
        perror("epoll_ctl del failed");
        return -1;
    }

    if (loop->handlers[fd]) {
        free(loop->handlers[fd]);
        loop->handlers[fd] = NULL;
    }

    return 0;
}

// 事件循环
void event_loop(event_loop_t *loop) {
    if (!loop) {
        fprintf(stderr, "event_loop: invalid loop\n");
        return;
    }

    struct epoll_event events[MAX_EVENTS];
    int nfds, i;

    while (1) {
        nfds = epoll_wait(loop->epoll_fd, events, MAX_EVENTS, EVENT_LOOP_TIMEOUT);
        if (nfds == -1) {
            perror("epoll_wait failed");
            continue;
        }

        for (i = 0; i < nfds; ++i) {
            int fd = events[i].data.fd;
            int revents = events[i].events;

            if (fd >= 0 && fd < MAX_EVENTS && loop->handlers[fd]) {
                loop->handlers[fd]->callback(fd, revents, loop->handlers[fd]->arg);
            }
        }
    }
}

// 销毁事件循环
void event_loop_destroy(event_loop_t *loop) {
    if (loop) {
        close(loop->epoll_fd);
        for (int i = 0; i < MAX_EVENTS; ++i) {
            if (loop->handlers[i]) {
                free(loop->handlers[i]);
            }
        }
        free(loop);
    }
}

// 示例回调函数：处理新连接
void on_accept(int fd, int events, void *arg) {
    int listen_fd = *(int *)arg;
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int client_fd = accept(listen_fd, (struct sockaddr *)&client_addr, &client_len);
    if (client_fd == -1) {
        perror("accept failed");
        return;
    }
    printf("Accept new connection from %s:%d on fd %d\n",
           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), client_fd);

    // 设置为非阻塞
    int flags = fcntl(client_fd, F_GETFL, 0);
    if (flags == -1 || fcntl(client_fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl nonblock failed");
        close(client_fd);
        return;
    }

    // 注册读事件
    event_loop_t *loop = (event_loop_t *)((char *)arg + sizeof(int)); // 传递 loop 指针
    event_add(loop, client_fd, EPOLLIN, on_read, NULL);
}

// 示例回调函数：处理读事件
void on_read(int fd, int events, void *arg) {
    char buffer[1024];
    ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
    if (bytes_read > 0) {
        printf("Read %zd bytes from fd %d: %.*s\n", bytes_read, fd, (int)bytes_read, buffer);
        // 回显数据
        write(fd, buffer, bytes_read);
    } else if (bytes_read == 0) {
        printf("Connection closed on fd %d\n", fd);
        event_loop_t *loop = (event_loop_t *)arg; // 在实际应用中可能需要传递 loop 指针
        event_del(loop, fd);
        close(fd);
    } else {
        perror("read failed");
        event_loop_t *loop = (event_loop_t *)arg; // 在实际应用中可能需要传递 loop 指针
        event_del(loop, fd);
        close(fd);
    }
}

int main() {
    int listen_fd;
    struct sockaddr_in server_addr;
    event_loop_t *loop;

    // 创建监听 socket
    listen_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (listen_fd == -1) {
        perror("socket failed");
        return EXIT_FAILURE;
    }

    // 绑定地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(8888);
    if (bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind failed");
        close(listen_fd);
        return EXIT_FAILURE;
    }

    // 监听
    if (listen(listen_fd, 10) == -1) {
        perror("listen failed");
        close(listen_fd);
        return EXIT_FAILURE;
    }

    // 创建事件循环
    loop = event_loop_create();
    if (!loop) {
        close(listen_fd);
        return EXIT_FAILURE;
    }

    printf("Server listening on port 8888...\n");

    // 注册监听 socket 的读事件 (新连接)
    // 注意：这里将 loop 指针也传递给 on_accept 回调
    struct {
        int fd;
        event_loop_t *loop;
    } accept_arg = {listen_fd, loop};
    event_add(loop, listen_fd, EPOLLIN, on_accept, &accept_arg);

    // 运行事件循环
    event_loop(loop);

    // 清理
    event_loop_destroy(loop);
    close(listen_fd);

    return EXIT_SUCCESS;
}